package com.ag.improvedjava.iterable;

import java.util.Comparator;
import java.util.Iterator;

final class Contains<T> {

	private final Iterable<T> iterable;
	private final T value;
	private final Comparator<T> comparer;

	Contains(Iterable<T> iterable, T value) {
		this.iterable = iterable;
		this.value = value;
		this.comparer = equalityComparator();
	}

	Contains(Iterable<T> iterable, T value, Comparator<T> comparer) {
		this.iterable = iterable;
		this.value = value;
		this.comparer = (comparer == null) ? equalityComparator() : comparer;
	}

	boolean value() {
		Iterator<T> it = iterable.iterator();
		while (it.hasNext()) { 
			if (comparer.compare(it.next(), value) == 0) {
				return true;
			}
		}
		return false;
	}
	
	private Comparator<T> equalityComparator() {
		return new Comparator<T>() {
			@Override
			public int compare(T o1, T o2) {
				return o1.equals(o2) ? 0 : -1;
			}
		};
	}
}